package com.habitsoft.glassfish.dashboard.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.habitsoft.kiyaa.util.AsyncCallbackProxy;
import com.habitsoft.kiyaa.views.GeneratedHTMLView;
import com.habitsoft.kiyaa.views.TableView.RowStyleHandler;

public abstract class StatView implements GeneratedHTMLView {

    Dashboard controller;
    JvmStats jvmStats = new JvmStats();
    Labels labels = GWT.create(Labels.class);
    
    RowStyleHandler<MemoryPoolInfo> rowStyleHandler = new RowStyleHandler<MemoryPoolInfo>() {
        public String getStyle(int rowNumber, MemoryPoolInfo pool) {
            return getUsedClass(pool.getUsed(), pool.getSize())+(pool.getName().startsWith("Total ")?" total":"");
        }
    };
    
    public void load(AsyncCallback<Void> callback) {
        controller.getStats().getJvmStats(new AsyncCallbackProxy<JvmStats>(callback) {
            public void onSuccess(JvmStats result) {
                jvmStats = result;
                super.onSuccess(result);
            }
        });
    }
    
    protected String getHeapSizeString() {
        return formatSize(jvmStats.getHeapSize());
    }
    
    protected String getMaxHeapSizeString() {
        return formatSize(jvmStats.getMaxHeapSize());
    }
    
    protected MemoryPoolInfo[] getMemoryPools() {
        if(jvmStats == null) return new MemoryPoolInfo[0];
        return jvmStats.memoryPools;
    }

    protected int getThreadCount() {
        return jvmStats.getThreadCount();
    }
    
    protected String formatSize(long heapSize) {
        // TODO Show MB, KB, or something if the number is pretty big
        return NumberFormat.getDecimalFormat().format(heapSize);
    }

    public Dashboard getController() {
        return controller;
    }

    public void setController(Dashboard controller) {
        this.controller = controller;
    }

    public JvmStats getJvmStats() {
        return jvmStats;
    }

    public void setJvmStats(JvmStats jvmStats) {
        this.jvmStats = jvmStats;
    }

    protected Labels getLabels() {
        return labels;
    }

    protected void setLabels(Labels labels) {
        this.labels = labels;
    }
    
    protected String getUsedClass(long used, long max) {
        if(used > ((max*9)/10)) {
            return "over-90-percent-used";
        }
        if(used > ((max*3)/4)) {
            return "over-3-quarters-used";
        }
        if(used > (max/2)) {
            return "over-1-half-used";
        }
        return "less-than-half-used";
    }

    public RowStyleHandler<MemoryPoolInfo> getRowStyleHandler() {
        return rowStyleHandler;
    }

    public void setRowStyleHandler(RowStyleHandler<MemoryPoolInfo> rowStyleHandler) {
        this.rowStyleHandler = rowStyleHandler;
    }
}
